"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 三权分立关闭时存在INDENDPENDT用户表时整库备份,赋权给管理员用户
Create At   : 2022-03-17
Owner       : opentestcase041
Description :
    1.查询参数enableSeparationOfDuty值
    2.创建数据库
    3.新数据库下创建用户
    4.independent用户登录新数据库创建表
    5.赋权给sysadmin用户
    6.gs_dump进行备份
    7.清理环境
Expect      :
    1.默认值off
    2.成功
    3.成功
    4.成功
    5.成功
    6.出现only user {self.user_name}_indent can do it
    7.成功
History     :
"""


import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class ModifyCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.dbuserNode = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.database_name = 'd_security_indentprivilege_0038'
        self.table_name = 't_security_indentprivilege_0038'
        self.user_name1 = 'u_security_indentprivilege_0038_01'
        self.user_name2 = 'u_security_indentprivilege_0038_02'
        self.default_value = self.common.show_param('enableSeparationOfDuty')
        self.dump_path = os.path.join(macro.DB_INSTANCE_PATH,
                                      f'{self.table_name}.sql')

    def test_security(self):
        text = '----step1:查询参数enableSeparationOfDuty值; expect:默认off----'
        self.log.info(text)
        if self.default_value != 'off':
            mod_msg = self.pri_sh.execute_gsguc('set',
                                                self.constant.GSGUC_SUCCESS_MSG,
                                                'enableSeparationOfDuty=off')
            self.assertTrue(mod_msg, '执行失败:' + text)
            result = self.pri_sh.restart_db_cluster()
            self.assertTrue(result, '执行失败' + text)

        text = '----step2:创建数据库 expect:成功----'
        self.log.info(text)
        sql_cmd = self.primary_sh.execut_db_sql(f'''
                drop database if exists {self.database_name};
                create database {self.database_name};''')
        self.log.info(sql_cmd)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, sql_cmd,
                      "执行失败:" + text)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_cmd,
                      "执行失败:" + text)

        text = '-----step3：新数据库下创建用户 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop user if exists {self.user_name1} cascade;" \
            f"drop user if exists {self.user_name2} cascade; " \
            f"create user {self.user_name1} independent createdb " \
            f"password '{macro.PASSWD_REPLACE}';" \
            f"create user {self.user_name2} sysadmin  " \
            f"password '{macro.PASSWD_REPLACE}'"
        msg = self.primary_sh.execut_db_sql(
            sql_cmd, sql_type=f' -U {self.dbuserNode.ssh_user} -W '
            f'{macro.PASSWD_REPLACE}', dbname=f'{self.database_name}')
        self.log.info(msg)
        self.assertTrue(msg.count
                        (self.constant.DROP_ROLE_SUCCESS_MSG) == 2,
                        '执行失败:' + text)
        self.assertEqual(msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         2, "执行失败:" + text)

        text = '-----step4：independent用户登录新数据库创建表 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop table if exists {self.table_name} cascade;" \
            f"create table {self.table_name}(id int,address text);"
        msg = self.primary_sh.execut_db_sql(
            sql_cmd, sql_type=f' -U {self.user_name1} -W '
            f'{macro.PASSWD_REPLACE}', dbname=f'{self.database_name}')
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg,
                      '执行失败:' + text)

        text = '----step5:赋权给sysadmin用户 expect:成功----'
        self.log.info(text)
        sql_cmd = f'grant all on table {self.table_name} to {self.user_name2};'
        msg = self.primary_sh.execut_db_sql(
            sql_cmd, sql_type=f' -U {self.user_name1} -W '
            f'{macro.PASSWD_REPLACE}', dbname=f'{self.database_name}')
        self.log.info(msg)
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, msg,
                      "执行失败:" + text)

        text = '----step6:使用gs_dump备份 ' \
               'expect:出现only user {self.user_name}_indent can do it----'
        self.log.info(text)
        sql_cmd = f"source {macro.DB_ENV_PATH};" \
            f"gs_dump -U  {self.user_name2} -W {macro.PASSWD_REPLACE} " \
            f"-p {self.dbuserNode.db_port} {self.database_name} " \
            f"-f {self.dump_path} -t " \
            f"{self.user_name1}.{self.table_name} -F p;"
        self.log.info(sql_cmd)
        msg = self.dbuserNode.sh(sql_cmd).result()
        self.log.info(msg)
        self.assertIn(f'only user {self.user_name1} can do it', msg,
                      "执行失败:" + text)

    def tearDown(self):
        text = '----step7:清理环境 expect:成功----'
        self.log.info(text)
        self.log.info('删除数据库')
        drop_cmd = self.primary_sh.execut_db_sql(f'''
            drop database {self.database_name};''')
        self.log.info(drop_cmd)
        self.log.info('删除用户')
        sql_cmd = self.primary_sh.execut_db_sql(
            f"drop user {self.user_name1} cascade;"
            f"drop user {self.user_name2} cascade;")
        self.log.info(sql_cmd)
        text = '-----删除备份文件-----'
        self.log.info(text)
        del_file = f'''rm -rf {self.dump_path}'''
        self.log.info(del_file)
        self.common.get_sh_result(self.dbuserNode, del_file)
        cmd = f'if [ -f {self.dump_path} ]; then echo "does exists"; ' \
            f'else echo "not exists"; fi'
        self.log.info(cmd)
        file_judgments = self.common.get_sh_result(self.dbuserNode, cmd)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_cmd,
                      "执行失败:" + text)
        self.assertTrue(sql_cmd.count
                        (self.constant.DROP_ROLE_SUCCESS_MSG) == 2,
                        '执行失败:' + text)
        self.assertIn('not exists', file_judgments, "执行失败" + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
